package threadlocal_test;

import java.util.Random;

/**
 * @author Ajie
 * @date 2021-03-17
 * @function  仿写ThreadLocal 核心逻辑 测试
 */
public class MyThreadLocal_Test {
    //随机休息1000到2000毫秒
    public static void randSleep() {

        Random random = new Random();

        int rand = random.nextInt(1000) + 1000;

        try {
            Thread.sleep(rand);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {

        final MyThreadLocal myThreadLocal = new MyThreadLocal();
        final MyThreadLocal myThreadLocal2 = new MyThreadLocal();

        Runnable task1 = () -> {
            for (int i = 0; i < 5; i++) {
                randSleep();
                myThreadLocal.set(i);
                myThreadLocal2.set("v"+i);
                int num = (int) myThreadLocal.get();
                System.out.println("thredl1 task1----------->threadlocal:" + num+"   threadlocal2:"+myThreadLocal2.get());
            }

        };

        Runnable task2 = () -> {

            for (int i = 5; i < 10; i++) {
                randSleep();
                myThreadLocal.set(i);
                myThreadLocal2.set("v"+i);
                int num = (int) myThreadLocal.get();
                System.out.println("thredl2 task2: threadlocal:" + num+"   threadlocal2:"+myThreadLocal2.get());
            }

        };

        new Thread(task1).start();

        new Thread(task2).start();

    }

}
